package com.onix.scalecamerapreview.camera;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;


import com.onix.scalecamerapreview.MyApplication;
import com.onix.scalecamerapreview.utils.Logger;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;



import static android.content.Context.MODE_PRIVATE;

/**
 * Author: livesun
 * Date: 2018/8/21 19:22
 * Description:
 */
public class FileUtils {
    public static String  init(){
        String initPath =null;
        List<File> mStorageList = new ArrayList<>();
        String[] paths = getVolumePaths(Applicarion.sInstance);
        if (paths != null && paths.length > 0) {
            for (String path : paths) {
                File file = new File(path);
                mStorageList.add(file);
            }
        }
        if(mStorageList.size() == 0){
            initPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        }else {
            initPath= mStorageList.get(0).getAbsolutePath();
        }
        return initPath;
    }

    public static String[] getVolumePaths(Context context) {
        return getVolumePathsFor14(context);
    }

    private static String[] getVolumePathsFor14(Context context) {
        List<String> availablePaths = new ArrayList<>();
        StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
        try {
            Method methodGetPaths = storageManager.getClass().getMethod("getVolumePaths");
            Method methodGetStatus = storageManager.getClass().getMethod("getVolumeState", String.class);
            String[] paths = (String[]) methodGetPaths.invoke(storageManager);

            for (String path : paths) {
                String status = (String) (methodGetStatus.invoke(storageManager, path));
                if (status.equals(Environment.MEDIA_MOUNTED)) {
                    availablePaths.add(path);
                }
            }
        } catch (Exception e) {
            Log.e("filemanager", "getVolumePathsFor14 >>> " + e.toString());
        }
        if (availablePaths.size() > 0) {
            String[] strings = new String[availablePaths.size()];
            availablePaths.toArray(strings);
            return strings;
        } else {
            return null;
        }
    }

    private static String SDPATH = "";

    /**
     * 获取到sd卡的根目录，并以String形式返回
     *
     * @return
     */
    public static String getSDCardPath() {
        return init();
    }

    /**
     * 创建文件或文件夹文件名或问文件夹名
     */
    public static boolean createFile() {
        if(!TextUtils.isEmpty(getSDCardPath())){
            File file = new File(getSDCardPath() + File.separator+ "masterQR");
            if(file!=null&&!file.exists()){
                file.mkdir();
            }
            SDPATH = file.getAbsolutePath();
            return true;
        }
        return  false;
    }

    /**
     * 创建文件或文件夹文件名或问文件夹名
     */
    public static String createDocFile() {
        if(!TextUtils.isEmpty(getSDCardPath())){
            File file = new File(getSDCardPath() +File.separator+ "masterQR"+File.separator+"MyDoc");
            if(file!=null&&!file.exists()){
                file.mkdirs();
            }
            return file.getAbsolutePath();
        }
        return null;
    }

    /**
     * 获取私有目录
     * @return
     */
    public static String createPrivateDocFilePath() {
        File myDoc = Applicarion.sInstance.getDir("MyDoc", MODE_PRIVATE);
        if(myDoc!=null&&!myDoc.exists()){
            myDoc.mkdir();
        }
        return myDoc.getAbsolutePath();
    }


    public static String getSdPath() {
        return SDPATH;
    }



    /**
     * 获取文件大小
     *
     * @param file 文件
     * @return 文件大小
     */
    public static String getFileSize(final File file) {
        long len = getFileLength(file);
        return len == -1 ? "" : byte2FitMemorySize(len);
    }

    /**
     * 获取文件长度
     *
     * @param file 文件
     * @return 文件长度
     */
    public static long getFileLength(final File file) {
        if (!isFile(file)) return -1;
        return file.length();
    }

    /**
     * 字节数转合适内存大小
     * <p>保留3位小数</p>
     *
     * @param byteNum 字节数
     * @return 合适内存大小
     */
    @SuppressLint("DefaultLocale")
    private static String byte2FitMemorySize(final long byteNum) {
        if (byteNum < 0) {
            return "shouldn't be less than zero!";
        } else if (byteNum < 1024) {
            return String.format("%.2fB", (double) byteNum + 0.05);
        } else if (byteNum < 1048576) {
            return String.format("%.2fKB", (double) byteNum / 1024 + 0.05);
        } else if (byteNum < 1073741824) {
            return String.format("%.2fMB", (double) byteNum / 1048576 + 0.05);
        } else {
            return String.format("%.2fGB", (double) byteNum / 1073741824 + 0.05);
        }
    }

    /**
     * 判断是否是文件
     *
     * @param file 文件
     * @return {@code true}: 是<br>{@code false}: 否
     */
    public static boolean isFile(final File file) {
        return isFileExists(file) && file.isFile();
    }

    /**
     * 判断文件是否存在
     *
     * @param file 文件
     * @return {@code true}: 存在<br>{@code false}: 不存在
     */
    public static boolean isFileExists(final File file) {
        return file != null && file.exists();
    }

    public static boolean deleteFile(String imageUrl) {
        if(TextUtils.isEmpty(imageUrl)){
            return false;
        }

        File file = new File(imageUrl);
        if(file!=null&&file.exists()){
            return file.delete();
        }
        return false;
    }


    /**
     * 获取language的私有目录
     * @return
     */
    public static String getPrivateLanguagePath(){
        File language = MyApplication.getInstance().getApplicationContext().getDir("localLanguage", MODE_PRIVATE);
        if(language!=null&&!language.exists()){
            language.mkdir();
        }
        return language.getAbsolutePath();
    }

    public static boolean writeLanguageFile(String content){
        String privateLanguagePath = getPrivateLanguagePath();
        if(TextUtils.isEmpty(privateLanguagePath)){
            return false;
        }
        //删除空格换行符

        String path = privateLanguagePath+File.separator+"Language.json";
        File file = new File(path);
        if(file.exists()){
            file.delete();
        }
        try {
            PrintWriter printWriter = new PrintWriter(file);
            printWriter.write(content);
            printWriter.close();
            if(printWriter.checkError()){
                Logger.e("Language","写入本地language文件失败 文件地址："+path);
                return false;
            }else {
                Logger.e("Language","写入本地language文件成功 文件地址："+path);
                return true;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String readeLanguageFile(){
        String privateLanguagePath = getPrivateLanguagePath();
        if(TextUtils.isEmpty(privateLanguagePath)){
            return null;
        }
        String path = privateLanguagePath+File.separator+"Language.json";
        File file = new File(path);
        if(!file.exists()){
            return null;
        }
        FileReader fr2 = null;
        BufferedReader bufr = null;
        StringBuffer stringBuffer = new StringBuffer();
        try {
            fr2 = new FileReader(file);
            bufr = new BufferedReader(fr2);
            String line = null;
            while((line = bufr.readLine())!=null) {
                System.out.println(line);
                stringBuffer.append(line);
            }
            Logger.e("Language","language存入到本地文件成功 文件地址："+path);
        }catch(IOException e) {
            stringBuffer.setLength(0);
            Logger.e("Language","language存入到本地文件夹失败");
        }finally {
            try {
                if(bufr!=null)
                    bufr.close();
            }catch(IOException e) {
                Logger.e("Language","language输出流关闭失败");
            }
        }
        return stringBuffer.toString();
    }



    private static boolean fileExists(File file){
        if(file!=null&&file.exists()){
            return true;
        }
        return false;
    }

    /**
     * 文件复制
     * @param s 源文件
     * @param t 目标文件
     */
    public static boolean fileChannelCopy(File s, File t) {
        boolean copySucess = false;
        FileInputStream fi = null;

        FileOutputStream fo = null;

        FileChannel in = null;

        FileChannel out = null;

        try {

            fi = new FileInputStream(s);

            fo = new FileOutputStream(t);

            in = fi.getChannel();//得到对应的文件通道

            out = fo.getChannel();//得到对应的文件通道

            in.transferTo(0, in.size(), out);//连接两个通道，并且从in通道读取，然后写入out通道
            Uri uri = Uri.fromFile(new File(t.getAbsolutePath()));
           Applicarion.sInstance.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            copySucess = true;
        } catch (IOException e) {
            copySucess = false;
            e.printStackTrace();
        } finally {
            try {
                fi.close();

                in.close();

                fo.close();

                out.close();

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return copySucess;

    }
}
